<?php

/**
 * 默认控制器
 */
class Controller_Rulesetting extends Controller_Abstract
{

	/**1**/
	/*Host Manage*/
	function actionRuleAddform()
    {
		if(!$this->_app->currentUserRoles())
			return $this->_redirect(url('default/login'));
		
		$show_box['title'] = '添加新规则　';
		Operate::everyOperate($_SESSION['acl_task_userdata']['account'],'',$_SESSION['acl_task_userdata']['group_name'],''.$show_box['title'],'');
		$show_box['posttype']='';
		//dump(Q::cache('rightitem'));
        $show_box['form'] = new Form_RuleAdd(url('default::rulesetting/ruleaddform'));
        $show_box['form']->_subject = $show_box['title'];

		if(Q::cache('rightitem')!=''){
			//重置下拉菜单
			$parent_id_items = Hostgroup::find('id in ('.Q::cache('rightitem').')')
				//->order('name ASC')
				->getAll()
				->toHashMap('id', 'groupname');
			//$parent_id_items['0'] = '全局规则1';
			ksort($parent_id_items);
			$show_box['form']['groupid']->items = $parent_id_items;
		}

        if ($this->_context->isPOST() && $show_box['form']->validate($_POST))
        {
			$edit_one = Config::find('keyword = ? and category = ? and ruleflag =? and groupid =?', $_POST['keyword'],$_POST['category'],$_POST['ruleflag'],$_POST['groupid'])->query();
			if(!$edit_one->id())
			{
				try{
					$user = new Config($this->_encodeUTF8($show_box['form']->values()));
					$user->save();
					return '';
				}catch (QDB_ActiveRecord_ValidateFailedException $ex){
					$show_box['form']->invalidate($ex);
					$show_box['posttype']=$_POST['category'];
				}
			}else{
				return '　';
			}
        }

		
        $this->_view['show_box'] = $show_box;
        $this->_viewname = 'form';
		//$this->_view['form'] = new Form_RuleAdd(url('default::rulesetting/add'));
    }

	/*Host Manage*/
	function actionRuleGLAddform()
    {
		if(!$this->_app->currentUserRoles())
			return $this->_redirect(url('default/login'));
		
		$show_box['title'] = '添加新规则　';
		Operate::everyOperate($_SESSION['acl_task_userdata']['account'],'',$_SESSION['acl_task_userdata']['group_name'],''.$show_box['title'],'');

        $show_box['form'] = new Form_RuleAdd(url('default::rulesetting/ruleaddform'));
		//$show_box['form']->import(array('ruleflag'=>'0'));
        $show_box['form']->_subject = $show_box['title'];

		if(Q::cache('rightitem')!=''){
			//重置下拉菜单
			$parent_id_items = Hostgroup::find('id in ('.Q::cache('rightitem').')')
				//->order('name ASC')
				->getAll()
				->toHashMap('id', 'groupname');
			//$parent_id_items['0'] = '全局规则1';
			ksort($parent_id_items);
			$show_box['form']['groupid']->items = $parent_id_items;
		}

        if ($this->_context->isPOST() && $show_box['form']->validate($_POST))
        {
			$edit_one = Config::find('keyword = ? and category = ? and ruleflag =? and groupid =?', $_POST['keyword'],$_POST['category'],$_POST['ruleflag'],$_POST['groupid'])->query();
			if(!$edit_one->id())
			{
				try{
					$user = new Config($this->_encodeUTF8($show_box['form']->values()));
					$user->save();
					return '';
				}catch (QDB_ActiveRecord_ValidateFailedException $ex){
					$show_box['form']->invalidate($ex);
				}
			}else{
				return '　';
			}
        }else{
			$show_box['form']->element('ruleflag')->set('selected', '0');
		}

        $this->_view['show_box'] = $show_box;
        $this->_viewname = 'form';

		//$this->_view['form'] = new Form_RuleAdd(url('default::rulesetting/add'));
		//$this->_view['form']->import(array('ruleflag'=>'0'));
    }

	/*Host Manage*/
	function actionRuleBJAddform()
    {
		if(!$this->_app->currentUserRoles())
			return $this->_redirect(url('default/login'));

		$show_box['title'] = '添加新规则　';
		Operate::everyOperate($_SESSION['acl_task_userdata']['account'],'',$_SESSION['acl_task_userdata']['group_name'],''.$show_box['title'],'');

        $show_box['form'] = new Form_RuleAdd(url('default::rulesetting/ruleaddform'));
		//$show_box['form']->import(array('ruleflag'=>'1'));
        $show_box['form']->_subject = $show_box['title'];

		if(Q::cache('rightitem')!=''){
			//重置下拉菜单
			$parent_id_items = Hostgroup::find('id in ('.Q::cache('rightitem').')')
				//->order('name ASC')
				->getAll()
				->toHashMap('id', 'groupname');
			//$parent_id_items['0'] = '全局规则1';
			ksort($parent_id_items);
			$show_box['form']['groupid']->items = $parent_id_items;
		}

        if ($this->_context->isPOST() && $show_box['form']->validate($_POST))
        {
			$edit_one = Config::find('keyword = ? and category = ? and ruleflag =? and groupid =?', $_POST['keyword'],$_POST['category'],$_POST['ruleflag'],$_POST['groupid'])->query();
			if(!$edit_one->id())
			{
				try{
					$user = new Config($this->_encodeUTF8($show_box['form']->values()));
					$user->save();
					return '';
				}catch (QDB_ActiveRecord_ValidateFailedException $ex){
					$show_box['form']->invalidate($ex);
				}
			}else{
				return '　';
			}
        }else{
			$show_box['form']->element('ruleflag')->set('selected', '1');
		}

        $this->_view['show_box'] = $show_box;
        $this->_viewname = 'form';
    }

	function actionModify(){
		
		if(!$this->_app->currentUserRoles())
			return $this->_redirect(url('default/login'));
		
		$show_box['title'] = '修改规则　';
		Operate::everyOperate($_SESSION['acl_task_userdata']['account'],'',$_SESSION['acl_task_userdata']['group_name'],''.$show_box['title'],'');
		$show_box['posttype']='';
		//dump(Q::cache('rightitem'));
        $show_box['form'] = new Form_RuleAdd(url('default::rulesetting/modify'));
        $show_box['form']->_subject = $show_box['title'];

		
		
		if(Q::cache('rightitem')!=''){
			//重置下拉菜单
			$parent_id_items = Hostgroup::find('id in ('.Q::cache('rightitem').')')
				//->order('name ASC')
				->getAll()
				->toHashMap('id', 'groupname');
			//$parent_id_items['0'] = '全局规则1';
			ksort($parent_id_items);
			$show_box['form']['groupid']->items = $parent_id_items;
		}

        if ($this->_context->isPOST() && $show_box['form']->validate($_POST))
        {
			$edit_one = Config::find('keyword = ? and category = ? and ruleflag =? and groupid =? and rulename = ?', $_POST['keyword'],$_POST['category'],$_POST['ruleflag'],$_POST['groupid'],$_POST['rulename'])->query();

			$edit_one_2 = Config::find('rulename = ? and ruleflag = ? and groupid =?', $_POST['rulename'],$_POST['ruleflag'],$_POST['groupid'])->query();
			$show_box['form']['ruleno']->set('value',$_POST['ruleno']);
			$edit_one_m = Config::find('id = ?', $_POST['ruleno'] )->query();
			//dump($edit_one_2->id());
			if($edit_one_m->id() && !$edit_one->id())
			{
				//dump($edit_one_m->id());
				
				if(!$edit_one_2->id() || $edit_one_2->id()==$edit_one_m->id()){
				try{
					//$user = new Config($this->_encodeUTF8($show_box['form']->values()));
					//dump($this->_encodeUTF8($show_box['form']->values()));
					$edit_one_m->changeProps($this->_encodeUTF8($show_box['form']->values()));
					$edit_one_m->save();
					return '';
				}catch (QDB_ActiveRecord_ValidateFailedException $ex){
					$show_box['form']->invalidate($ex);
					//$show_box['posttype']=$_POST['category'];
				}
				}else{
					if($edit_one_2->id()!=$edit_one_m->id())
						$show_box['form']['rulename']->invalidate("规则名已存在！");
				}
			}else{
				//return '　';
			}
        }else if (!$this->_context->isPOST()){
			// 查询指定用户 ID
			$edit_one_m = Config::find('id = ?', $this->_context->id )->query();
			if ( !$edit_one_m->id() )
			{ // 如果用户 ID 无效，则返回用户管理首页
				return $this->_redirect(url('default::rulesetting/index'));
			}
			
			//$edit_one = Config::find('keyword = ? and category = ? and ruleflag =? and groupid =? and rulename = ?', $_POST['keyword'],$_POST['category'],$_POST['ruleflag'],$_POST['groupid'],$_POST['rulename'])->query();
			
			$edit_one_m['rulename']=iconv("GB2312","UTF-8",$edit_one_m['rulename']);
			$edit_one_m['cncategory']=iconv("GB2312","UTF-8",$edit_one_m['cncategory']);
			$edit_one_m['keyword']=iconv("GB2312","UTF-8",$edit_one_m['keyword']);

			$show_box['form']->import($edit_one_m);
			//$show_box['form']->add(QForm::ELEMENT, 'ruleno', array('_ui' => 'hidden','value' => $this->_context->id));
			$show_box['form']['flag']->set('value',$this->_context->flag);
			$show_box['form']['ruleno']->set('value',$this->_context->id);
		}

		
        $this->_view['show_box'] = $show_box;
        $this->_viewname = 'form_m';
	}

	/**1**/
	function actionDel()
    {
        $show_box['title'] = '删除规则';
        if ($this->_app->currentUserRoles())
        {
		Operate::everyOperate($_SESSION['acl_task_userdata']['account'],'',$_SESSION['acl_task_userdata']['group_name'],''.$show_box['title'],'');
		//注意设定用户删除的锁定
        if($this->_context->id)
        {
        	$rid = $this->_context->id;
        	Config::meta()->destroyWhere('id = ?', $rid);
        	if(mysql_affected_rows())
        	{
        		return $this->_redirectMessage(
                '规则删除成功', 
                '指定规则删除成功',
                url('default::default/framework', array('control' => 'rulesetting','acts' => 'index|ruleaddform')));
        	}
        	else
        	{
        		return $this->_redirectMessage(
                '规则删除失败', 
                '指定规则删除失败',
                url('default::default/framework', array('control' => 'rulesetting','acts' => 'index|ruleaddform')));
        	}
        }
        else
        {
        	return $this->_redirectMessage(
                '错误操作', 
                '操作错误，返回首页',
                url('default::default/framework', array('control' => 'rulesetting','acts' => 'index|ruleaddform')));
        }

		}
        else
        {
            // 未登录则转到登录页面
            return $this->_redirect(url('default/login'));
        }
    }
	
    /**1**/
    function actionIndex()
    {
        $show_box['title'] = '规则设置首页';$this->_view['gid'] = '';$this->_view['rightstr'] = '';
		$groupno=0;$this->_view['flagstr'] = '';$flags='';
        if ($this->_app->currentUserRoles())
        {
			Operate::everyOperate($_SESSION['acl_task_userdata']['account'],'',$_SESSION['acl_task_userdata']['group_name'],''.$show_box['title'],'');
			//区分用户
			 $os = array("admin");

		     $aroles = array();
		     $aroles =split('[,]', $_SESSION['acl_task_userdata']['roles']);
			//dump($aroles);
			$isrightp=false;
			 foreach ($aroles as $value){
				if (in_array(strtolower($value), $os)) {
					$isrightp=true;
					//echo 'opip';
					break;
					//echo "Got Irix";
				}
			 }
			 //echo $isrightp;
			 //echo $_SESSION['acl_task_userdata']['user_id'];
			 $adming='';
			 if(!$isrightp){
				$havegroups = array();
				$select1 = Groupuser::find('userid = ?',$_SESSION['acl_task_userdata']['user_id'])->getAll();
				foreach ($select1 as $av){
					array_push($havegroups,$av->groupid);
					//echo $av->groupid;
				}
				$addconds='';
				//dump($havegroups);
				$hgs=count($havegroups);
				$this->_view['adming']=$hgs;
				if($hgs>0){
					//$groupno=''.join(",",$havegroups).'';
					$groupno='0';
				}else{
					$groupno='0';
				}
			 }else{
				
				$this->_view['adming']=-1;
			 }
			 //END
			
			
			if(Q::cache('rightitem')!='')
				$this->_view['rightstr'] = '1';

			if(isset($this->_context->flag)){
				$this->_view['flagstr'] = $this->_context->flag;
				$flags=' and ruleflag = '.str_replace("flag_","",$this->_context->flag).' ';
			}else{

				if(isset($this->_context->id)){
					$groupno=$this->_context->id;
					$this->_view['gid'] = $this->_context->id;
				}
			}

			//dump($flags);
			// 设置页面列表数目
			$pagesize = 10;
			// 获取当前页数，通常为get方式参数
			$page = $this->_context->page;
			$this->_view['pageno']=$page;

			$select = Config::find('groupid in ('.$groupno.')'.$flags)->limitPage($page, $pagesize);
			$this->_view['pager'] = $select->getPagination();
			$this->_view['group'] = $select->order("id desc")->getAll();
			
			if($this->_view['pager']['record_count']>0 && $page=='')
				$page=1;

			$this->_view['countno'] = $this->_view['pager']['page_size']*($page-1)+1;

			$pagediv = new Helper_JsPager($this->_view['pager']['record_count'], $this->_view['pager']['page_size'], 9, $page, 'opgopage(\'rulesetting|index|','\')',5);
			$this->_view['pagestr']= $pagediv->show();
        }
        else
        {
            // 未登录则转到登录页面
            return $this->_redirect(url('default/login'));
        }
    }

	/**1**/
	function actionIndexguolv()
    {
        $show_box['title'] = '过滤规则设置首页';
		$groupno=0;$this->_view['gid'] = '';$this->_view['flagstr'] = '';$this->_view['rightstr'] = '';
        if ($this->_app->currentUserRoles())
        {
			Operate::everyOperate($_SESSION['acl_task_userdata']['account'],'',$_SESSION['acl_task_userdata']['group_name'],''.$show_box['title'],'');
			if(Q::cache('rightitem')!='')
				$this->_view['rightstr'] = '1';
			if(isset($this->_context->id)){
				$groupno=$this->_context->id;
				$this->_view['gid'] = $this->_context->id;
			}
			// 设置页面列表数目
			$pagesize = 10;
			// 获取当前页数，通常为get方式参数
			$page = $this->_context->page;
			$this->_view['pageno']=$page;
			$select = Config::find('ruleflag = ? and groupid = ?','0',$groupno)->limitPage($page, $pagesize);
			$this->_view['pager'] = $select->getPagination();
			$this->_view['group'] = $select->order("id desc")->getAll();
			//$this->_view['countno'] = $this->_view['pager']['page_size']*$page+1;
			if($this->_view['pager']['record_count']>0 && $page=='')
				$page=1;

			$this->_view['countno'] = $this->_view['pager']['page_size']*($page-1)+1;
			
			$pagediv = new Helper_JsPager($this->_view['pager']['record_count'], $this->_view['pager']['page_size'], 9, $page, 'opgopage(\'rulesetting|indexguolv|','\')',5);
			$this->_view['pagestr']= $pagediv->show();
        }
        else
        {
            // 未登录则转到登录页面
            return $this->_redirect(url('default/login'));
        }
    }

	/**1**/
	function actionRules()
    {
		$show_box['title'] = '组规则设置首页';
        if ($this->_app->currentUserRoles())
        {
			//区分用户
			 $os = array("admin");

		     $aroles = array();
		     $aroles =split('[,]', $_SESSION['acl_task_userdata']['roles']);
			//dump($aroles);
			$isrightp=false;
			 foreach ($aroles as $value){
				if (in_array(strtolower($value), $os)) {
					$isrightp=true;
					//echo 'opip';
					break;
					//echo "Got Irix";
				}
			 }
			 //echo $isrightp;
			 //echo $_SESSION['acl_task_userdata']['user_id'];
			 $adming='';
			 if(!$isrightp){
				$havegroups = array();
				$select1 = Groupuser::find('userid = ?',$_SESSION['acl_task_userdata']['user_id'])->getAll();
				foreach ($select1 as $av){
					array_push($havegroups,$av->groupid);
					//echo $av->groupid;
				}
				$addconds='';
				//dump($havegroups);
				$hgs=count($havegroups);
				$this->_view['adming']=$hgs;
				if($hgs>0){
					$adming=' id in ('.join(",",$havegroups).') ';
				}else{
					$adming=' id in (-1) ';
				}
			 }else{
				
				$this->_view['adming']=-1;
			 }
			 //END
			
			
			Operate::everyOperate($_SESSION['acl_task_userdata']['account'],'',$_SESSION['acl_task_userdata']['group_name'],''.$show_box['title'],'');
			// 设置页面列表数目
			$pagesize = 10;
			// 获取当前页数，通常为get方式参数
			$page = $this->_context->page;
			$this->_view['pageno']=$page;
			$select = Hostgroup::find($adming)->limitPage($page, $pagesize);
			$this->_view['pager'] = $select->getPagination();
			$this->_view['group'] = $select->order("id desc")->getAll();
			//$this->_view['countno'] = $this->_view['pager']['page_size']*$page+1;
			if($this->_view['pager']['record_count']>0 && $page=='')
				$page=1;

			$this->_view['countno'] = $this->_view['pager']['page_size']*($page-1)+1;

			$pagediv = new Helper_JsPager($this->_view['pager']['record_count'], $this->_view['pager']['page_size'], 9, $page, 'opgopage(\'rulesetting|rules|','\')',5);
			$this->_view['pagestr']= $pagediv->show();

			//统计资料
			//SELECT count( 1 ) AS configs, groupid FROM `config` GROUP BY groupid
			$table =QDB::getConn();
			$sql = "SELECT count(id) AS configall, groupid FROM `config` GROUP BY groupid";
			$handel =$table->execute($sql);
			$temp2 = $handel->fetchAll();
			$achosts = array();
			foreach ($temp2 as $s){
				if(isset($s['configall']))
					$achosts[$s['groupid']]=$s['configall'];
				//array_push($achosts,$s['configall']);
			}
			$this->_view['group_config']= $achosts;
			//dump($achosts);
		}else
        {
            // 未登录则转到登录页面
            return $this->_redirect(url('default/login'));
        }
    }	

	/**1**/
	function actionIndexbaojing()
    {
        $show_box['title'] = '报警规则设置首页';
		$groupno=0;$this->_view['gid'] = '';$this->_view['flagstr'] = '';
		$this->_view['rightstr'] = '';
        if ($this->_app->currentUserRoles())
        {
			Operate::everyOperate($_SESSION['acl_task_userdata']['account'],'',$_SESSION['acl_task_userdata']['group_name'],''.$show_box['title'],'');
			if(Q::cache('rightitem')!='')
				$this->_view['rightstr'] = '1';
			if(isset($this->_context->id)){
				$groupno=$this->_context->id;
				$this->_view['gid'] = $this->_context->id;
			}
			// 设置页面列表数目
			$pagesize = 10;
			// 获取当前页数，通常为get方式参数
			$page = $this->_context->page;
			$this->_view['pageno']=$page;
			$select = Config::find('ruleflag = ? and groupid = ?','1',$groupno)->limitPage($page, $pagesize);
			$this->_view['pager'] = $select->getPagination();
			$this->_view['group'] = $select->order("id desc")->getAll();
			//$this->_view['countno'] = $this->_view['pager']['page_size']*$page+1;
			if($this->_view['pager']['record_count']>0 && $page=='')
				$page=1;

			$this->_view['countno'] = $this->_view['pager']['page_size']*($page-1)+1;

			$pagediv = new Helper_JsPager($this->_view['pager']['record_count'], $this->_view['pager']['page_size'], 9, $page, 'opgopage(\'rulesetting|indexbaojing|','\')',5);
			$this->_view['pagestr']= $pagediv->show();
        }
        else
        {
            // 未登录则转到登录页面
            return $this->_redirect(url('default/login'));
        }
    }

	/**1**/
	function actionIndexgroup()
    {
        $show_box['title'] = '组规则设置首页';$this->_view['gid'] = '';
        if ($this->_app->currentUserRoles())
        {
			Operate::everyOperate($_SESSION['acl_task_userdata']['account'],'',$_SESSION['acl_task_userdata']['group_name'],''.$show_box['title'],'');
			
			$groupno=$this->_context->id;

			if(isset($this->_context->groupid))
				$groupno=$this->_context->groupid;
			// 设置页面列表数目
			$pagesize = 10;
			// 获取当前页数，通常为get方式参数
			$page = $this->_context->page;
			$this->_view['pageno']=$page;
			$select = Config::find('groupid = ?',$groupno)->limitPage($page, $pagesize);
			$this->_view['pager'] = $select->getPagination();
			$this->_view['group'] = $select->order("id desc")->getAll();
			$this->_view['gid'] = $this->_context->id;
			//$this->_view['countno'] = $this->_view['pager']['page_size']*$page+1;
			if($this->_view['pager']['record_count']>0 && $page=='')
				$page=1;

			$this->_view['countno'] = $this->_view['pager']['page_size']*($page-1)+1;

			$pagediv = new Helper_JsPager($this->_view['pager']['record_count'], $this->_view['pager']['page_size'], 9, $page, 'opgopage(\'rulesetting|indexgroup|','\')',5);
			$this->_view['pagestr']= $pagediv->show();
        }
        else
        {
            // 未登录则转到登录页面
            return $this->_redirect(url('default/login'));
        }
    }

	protected function _encodeUTF8($array){



	   foreach($array as $key=>$value){

		//$key=iconv("GB2312","UTF-8",$key);
			if($key!=''){
	      $array[$key] = !is_array($value)?iconv("UTF-8","GB2312",$value):self::_encodeUTF8($array[$key]);
			}
			

	   }
	   $newarray=array();
		foreach($array as $key=>$value){
		//if($array[$key]!='')
			$newarray[iconv("UTF-8","GB2312",$key)]=$array[$key];
		
		}
		

	   return $newarray;



	}
}